import json
from string import Template
import os
from base.Interface import Request_processing
from base.Assertion_value import *
from log.log import Log
from jsonpath import jsonpath
from base.sql import sql_data

log = Log()


class Key_word:
    api_base = Request_processing()

    def __init__(self, parma):
        self.test_value = parma

    def data_processing(self):
        for key_test, value in self.test_value.items():
            # test_value=Template(str(value)).safe_substitute(os.environ)#上下文关联处理方法

            for test_value_key, test_value_data in value.items():
                a = Template(str(test_value_data)).safe_substitute(os.environ)
                test_value_data = eval(a)
                if hasattr(self.api_base, test_value_key):
                    self.a = getattr(self.api_base, test_value_key)
                    self.b = self.a(**test_value_data)
                elif test_value_key == 'assert':
                    Aseert().assert_value(test_value_data, self.b)
                elif hasattr(sql_data(), test_value_key):
                    for key_sql in test_value_data:
                        self.date = getattr(sql_data(), test_value_key)
                        try:
                            self.value = self.date(key_sql['sql'])
                        except:
                            if test_value_key == 'sql_assert':

                                if key_sql['ex_value']:
                                    Aseert().assert_sql(value=self.value, expected_value=key_sql['ex_value'][0],
                                                        number=key_sql['ex_value'][1])
                                else:
                                    Aseert().assert_sql(value=self.value, expected_value=key_sql['ex_value'],
                                                        )
                            elif test_value_key == "exc_sql":
                                for key, number in key_sql.items():
                                    if key != 'sql':
                                        try:
                                            os.environ[key] = str(list(self.value)[0][number])
                                            log.log_os(key, str(list(self.value)[0][number]))
                                        except:
                                            log.log_os_x(key)
                elif test_value_key == "exc":
                    """上下文关联值写入"""
                    for key, value in test_value_data.items():
                        try:
                            os.environ[key] = jsonpath(json.loads(self.b.text), value[0])[value[1]]
                            log.log_os(key, jsonpath(json.loads(self.b.text), value[0])[value[1]])
                        except TypeError:
                            raise TypeError("实际返回值中，找不到要提取的信息{}".format(value[0]))
                else:
                    log.log_action(test_value_key,key_test)

